package com.neuronbit.businessflow.plugin.task;

import com.neuronbit.businessflow.flow.BpmFile;
import com.neuronbit.businessflow.flow.project.Project;
import com.neuronbit.businessflow.plugin.GradleProject;
import org.gradle.api.DefaultTask;
import org.gradle.api.provider.Property;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.TaskAction;

import javax.inject.Inject;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.util.Set;

/**
 * The type Generate source code task.
 */
public abstract class GenerateSourceCodeTask extends DefaultTask {
    /**
     * Gets package name.
     *
     * @return the package name
     */
    @Input
    abstract public Property<String[]> getPackageName();

    /**
     * Instantiates a new Generate source code task.
     */
    @Inject
    public GenerateSourceCodeTask() {
        getPackageName().set(new String[0]);
    }

    /**
     * Generate.
     *
     * @throws IOException        the io exception
     * @throws XMLStreamException the xml stream exception
     */
    @TaskAction
    public void generate() throws IOException, XMLStreamException {
        Project project = new GradleProject.Builder(getProject(), "").build();

        Set<BpmFile> bpmFiles = project.scanBpmFiles();
        for (BpmFile bpmFile : bpmFiles) {
            try {
                bpmFile.generateJavaCode();
            } catch (Exception e) {
                getLogger().debug("generate java source code for {} failed", bpmFile, e);
                throw e;
            }
        }
    }
}
